﻿using AsscerMVCN2512.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;

namespace AsscerMVCN2512.Controllers
{
    public class DeptController : Controller
    {
        private readonly AssetDBEntities1 db = new AssetDBEntities1();

        // 部门列表页面
        public ActionResult Index()
        {
            return View();
        }

        // 获取部门列表数据
        [HttpPost]
        public ActionResult GetDeptList(int page = 1, int limit = 10, string DeptName = "", int? CampusID = null)
        {
            try
            {
                var query = from d in db.DeptInfo
                            join c in db.CampusInfo on d.CampusID equals c.CampusID into campus
                            from c in campus.DefaultIfEmpty()
                            select new
                            {
                                d.DeptID,
                                d.DeptName,
                                d.CampusID,
                                CampusName = c != null ? c.CampusName : "",
                                d.DeptReMark
                            };

                // 查询条件
                if (!string.IsNullOrEmpty(DeptName))
                    query = query.Where(d => d.DeptName.Contains(DeptName));

                if (CampusID.HasValue && CampusID > 0)
                    query = query.Where(d => d.CampusID == CampusID);

                var total = query.Count();
                var data = query.OrderByDescending(d => d.DeptID)
                              .Skip((page - 1) * limit)
                              .Take(limit)
                              .ToList();

                return Json(new { code = 0, msg = "成功", count = total, data = data });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        // 获取校区列表（用于部门所属校区选择）
        [HttpPost]
        public ActionResult GetCampusList()
        {
            try
            {
                var data = db.CampusInfo.Select(c => new { c.CampusID, c.CampusName }).ToList();
                return Json(new { code = 0, msg = "成功", data = data });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取校区列表失败：" + ex.Message });
            }
        }

        // 获取所有部门列表（用于其他模块的下拉选择）
        [HttpPost]
        public ActionResult GetAllDepts()
        {
            try
            {
                var data = db.DeptInfo.Select(d => new { d.DeptID, d.DeptName }).ToList();
                return Json(new { code = 0, msg = "成功", data = data });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取部门列表失败：" + ex.Message });
            }
        }

        // 添加部门
        [HttpPost]
        public ActionResult AddDept(DeptInfo dept)
        {
            try
            {
                // 验证部门名称唯一性
                var existingDept = db.DeptInfo.FirstOrDefault(d => d.DeptName == dept.DeptName && d.CampusID == dept.CampusID);
                if (existingDept != null)
                {
                    return Json(new { code = 1, msg = "该校区下已存在同名部门，请使用其他名称" });
                }

                db.DeptInfo.Add(dept);
                db.SaveChanges();

                return Json(new { code = 0, msg = "添加部门成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "添加部门失败：" + ex.Message });
            }
        }

        // 获取单个部门信息（用于编辑页面）
        [HttpGet]
        public ActionResult GetDeptById(int id)
        {
            try
            {
                var dept = db.DeptInfo.Find(id);
                if (dept == null)
                {
                    return Json(new { code = 1, msg = "部门不存在" }, JsonRequestBehavior.AllowGet);
                }

                return Json(new
                {
                    code = 0,
                    data = new
                    {
                        DeptID = dept.DeptID,
                        DeptName = dept.DeptName,
                        CampusID = dept.CampusID,
                        DeptRemark = dept.DeptReMark // 与前端保持字段名一致
                    }
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取部门信息失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        // 修改部门
        [HttpPost]
        public ActionResult UpdateDept(DeptInfo dept)
        {
            try
            {
                var existingDept = db.DeptInfo.Find(dept.DeptID);
                if (existingDept == null)
                {
                    return Json(new { code = 1, msg = "部门不存在" });
                }

                // 验证部门名称唯一性（排除当前部门）
                var existingWithSameName = db.DeptInfo.FirstOrDefault(d => d.DeptName == dept.DeptName && d.CampusID == dept.CampusID && d.DeptID != dept.DeptID);
                if (existingWithSameName != null)
                {
                    return Json(new { code = 1, msg = "该校区下已存在同名部门，请使用其他名称" });
                }

                // 更新字段
                existingDept.DeptName = dept.DeptName;
                existingDept.CampusID = dept.CampusID;
                existingDept.DeptReMark = dept.DeptReMark;

                db.Entry(existingDept).State = EntityState.Modified;
                db.SaveChanges();

                return Json(new { code = 0, msg = "修改部门成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "修改部门失败：" + ex.Message });
            }
        }

        // 删除部门
        [HttpPost]
        public ActionResult DeleteDept(int id)
        {
            try
            {
                var dept = db.DeptInfo.Find(id);
                if (dept == null)
                {
                    return Json(new { code = 1, msg = "部门不存在" });
                }

                // 检查是否有关联的员工
                var hasEmployees = db.EmpolyInfo.Any(e => e.DeptID == id);
                if (hasEmployees)
                {
                    return Json(new { code = 1, msg = "该部门下存在员工，无法删除" });
                }

                db.DeptInfo.Remove(dept);
                db.SaveChanges();
                return Json(new { code = 0, msg = "删除部门成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "删除部门失败：" + ex.Message });
            }
        }

        // 检查部门名称是否唯一
        [HttpPost]
        public ActionResult CheckDeptName(string deptName, int campusId, int? deptId = null)
        {
            try
            {
                var existing = db.DeptInfo.FirstOrDefault(d => d.DeptName == deptName && d.CampusID == campusId);
                if (existing != null && (deptId == null || existing.DeptID != deptId))
                {
                    return Json(new { code = 1, msg = "该校区下已存在同名部门" });
                }
                return Json(new { code = 0 });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "检查失败：" + ex.Message });
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
